<template>
    <div class="view page-gameMatch">
        <div class="timer">{{time | timeCount}}</div>
        <div class="m-con">
            <div class="matchBox clearfix">
                <div class="match-self">
                    <div class="avater">
                        <img :src="userInfo.userAvatar?userInfo.userAvatar:headError"  :onerror="headError">
                    </div>
                    <div class="name">{{userInfo.sstUserTruename}}</div>
                    <div class="classname">{{userInfo.classList[0].sstClassName}}</div>
                </div>
                <div class="match-self">
                    <div class="avater">
                        <img :src="matchInfo.userAvatar?matchInfo.userAvatar:headError" :onerror="headError" v-if="!loading">
                        <div class="match_loading" v-if="loading"></div>
                    </div>
                    <div class="name">{{matchInfo.name||'···'}}</div>
                    <div class="classname">{{matchInfo.classname||'···'}}</div>
                </div>
            </div>
            <div class="m-foot_btnBox">
                <div class="u-btn" @click="cancel">取消</div>
            </div>
        </div>
    </div>
</template>
<script>
import * as api from '@/api/index';
import gameAnswer from './answer';
export default {
    components:{
        gameAnswer
    },
    data(){
        return {
            time: 180,
            headError: this.$store.state.headError,
            userId: this.$store.state.userId,
            userInfo: JSON.parse(localStorage.getItem("userInfo")),
            themeId: getParames("themeId"),
            aid:'001',
            uid: this.$store.state.uid,
            uid_robot: this.$store.state.uid,
            robotId: new Date().getTime(),
            token:'',

            matchInfo:{},           //匹配的对手
            roomInfo:{},
            loading: true,
            socket: null,
            timeLoop: null,
            timeOut: null,
            isReceive: true,       //是否接收
            hasEnter: false,         //是否有人进入房间
            isRobot: 0,              //是否是机器人 1:是   机器人不能创建房间 只能去匹配房间
        }
    },
    filters:{
        timeCount(value){
            var minute = Math.floor(value/60);
            var second = value%60;
            minute = (minute<10)?'0'+minute:minute;
            second = (second<10)?'0'+second:second;
            return minute+":"+second
        },
    },
    mounted(){
        if (window.history && window.history.pushState) {
            history.pushState(null, null, document.URL);
            window.addEventListener('popstate', this.goBack, false);
        }
        document.addEventListener('visibilitychange',this.diffTime)
        // 防止页面手动刷新
        var roomInfo = this.$store.state.roomInfo
        if(!roomInfo || JSON.stringify(roomInfo) == '{}'){
            this.$router.push({path:'/game'})
            return false
        }
        this.createRoom()
        this.countTime()
    },
    methods:{
        goBack(){
            window.removeEventListener('popstate', this.goBack, false);
            this.cancel()
        },
        diffTime(){
            if (document.visibilityState =='hidden') {
                this.cancel()
                document.removeEventListener('visibilitychange', this.diffTime);
            } 
        },
        async createRoom(){
            var data = {
                isRobot: this.isRobot,                     //是否是机器人 1:是   机器人不能创建房间 只能去匹配房间
                themeId: this.themeId,
                futureId: this.userInfo.futureId,
                userId: this.isRobot==0?this.userId:this.robotId,
            }
            var res = await api.CreateRoom(data)
            if(res.resultCode == 1){
                if(this.isRobot == 0){
                    this.roomInfo = res.value
                    this.socketLogin()
                }else{ 
                    this.socket.emit('join',{'room':this.roomInfo.roomId,'data':JSON.stringify(this.roomInfo),'aid': "001",'uid': this.uid});
                }
            }else if(res.resultCode == 0 && this.isRobot == 1){
                this.isRobot = 0
            }
        },
        async socketLogin(){
            var data = {
                "aid": this.aid,  // 应用id
                "uid": this.uid, // 用户id
                "platform" : 0 // 当前客户端
            }
            var res = await api.socketLogin(data)
            this.token = res.Value.token
            
            this.getSocketInit()
        },
        /********
         * 初始化socket服务
         * server_response —— type: IM服务接口说明.md
         * server_response —— msgType： 1 加入房间  2 房间信息  3有人退出房间
         * 
         * **********/ 
        getSocketInit(){
            this.uid = this.roomInfo.roomId+"|"+this.userId;
            var namespace = '/socket.io.v1';
            let socketUrl = process.env.BASE_API_Socket?process.env.BASE_API_Socket:''
            var url = socketUrl + namespace;

            url += "?uid="+this.uid + "&aid="+this.aid; // 加上参数
            url += "&token=" + this.token;

            this.$store.dispatch('SocketConnect',url).then(res => {
                this.socket = res
                // 服务端消息接收接口
                this.socket && this.socket.on('server_response', (msg, cb) => {
                    const { type,msgType} = msg                
                    if(msgType&&msgType==1){        //加入房间
                        this.hasEnter = true
                        var info = msg.data?JSON.parse(msg.data):{}
                        this.getUserInfo(info.roomUserList)
                    }
                    if (cb) cb();
                    this.isReceive && console.log(msg)
                });
                this.socket.emit('join',{'room':this.roomInfo.roomId,'data':JSON.stringify(this.roomInfo),'aid': "001",'uid': this.uid});

                //  自己断网等情况...
                this.socket && this.socket.on('connect_error', () => {
                    if(this.isReceive){
                        this.$LayerTips({
                            content: "您已断开连接，请查看网络情况",
                            time: 1500
                        });  
                        setTimeout(()=>{
                            this.cancel()
                        },1500)
                    }
                })
            
            }).catch(error => {
                reject(error);
            });
        },
        // 获取个人信息
		async getUserInfo(list){
            var selfIndex = list.findIndex(item => {return item.userId == this.userId})
            var data = {
                userId: list[1-selfIndex].userId
            }
            var selfInfo = {
                self_name: this.userInfo.sstUserTruename,
                self_userAvatar: this.userInfo.userAvatar,
                self_classname: this.userInfo.classList[0].sstClassName
            }
            var roomDetail = {
                ...this.$store.state.roomInfo,
                ...selfInfo,
                roomId: this.roomInfo.roomId,
                num: list[selfIndex].num > list[1-selfIndex].num ? 1 : 0,           //抽签结果(大的先)  1先手   0后手
                order: list[selfIndex].order,       //进入顺序
            }
            // robot  是否匹配的是机器人
            if(list[1-selfIndex].robot){
                this.matchInfo = {
                    name: "机器人",
                    userAvatar: require("@/assets/img/robot.png"),
                    classname: '',
                    robotId: this.robotId
                }
                roomDetail = {
                    ...roomDetail,
                    ...this.matchInfo,
                    isRobot:1,
                }
                this.$store.dispatch("setRoomInfo",roomDetail)
                this.$router.replace({path:'gameAnswer'})
                return false
            }
            var res = await api.getUserInfo(data)
            if(res.resultCode == 1){
                this.loading = false
                var val = res.value?res.value:{}
                this.matchInfo = {
                    name: val.sstUserTruename,
                    userAvatar: val.userAvatar,
                    classname: val.classList&&val.classList.length?val.classList[0].sstClassName:'',
                }
                roomDetail = {
                    ...roomDetail,
                    ...this.matchInfo,
                    isRobot:0,
                }
                this.$store.dispatch("setRoomInfo",roomDetail)
                this.$router.push({path:'gameAnswer'})
            }
        },
        countTime(){
            this.timeLoop = setInterval(()=>{
                if(this.time>0){
                    this.time--
                    // 若过了20秒还是没有人进入  则安排机器人
                    if(this.time == 160 && !this.hasEnter){
                        this.isRobot = 1
                        this.createRoom()
                    }
                    // 服务端保持通讯（发送心跳）
                    this.socket && this.socket.emit('client_ping_pong', this.time);
                } else{
                    clearInterval(this.timeLoop)
                    this.$LayerTips({
                        content: "暂未有伙伴进入房间，请稍后再试",
                        time: 1500
                    });
                    this.timeOut = setTimeout(()=>{
                        this.cancel()
                    },1500)
                }
            },1000)
        },
        prepareSendData(text){
            return {
                aid : this.aid,
                uid: this.uid,
                data: text
            }
        },
        cancel(){
            clearInterval(this.timeLoop)
            clearTimeout(this.timeOut)
            if(this.socket){
                var data = this.prepareSendData('')
                console.log(data)
                this.socket.emit('leave',{'room':this.roomInfo.roomId,...data});
                this.socket.emit('disconnect_request', data);
                this.socket = null
                this.$store.dispatch('DisSocketConnect')
            }
			this.$router.push({path:'game'})
        },
    },
    destroyed(){
        // if(this.socket){
        //     var data = this.prepareSendData('')
        //     this.socket.emit('leave',{'room':this.roomInfo.roomId,...data});
        //     this.socket.emit('disconnect_request', data);
        //     this.socket = null
        // }
        this.isReceive = false
        clearInterval(this.timeLoop)
        document.removeEventListener('visibilitychange', this.diffTime)
    }
}
</script>